package controller.book;

import dao.book.BookDaoImp;
import model.Book;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet(name = "AddBookServlet", urlPatterns = "/addBook")
public class AddBookServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BookDaoImp dao = new BookDaoImp();
        String message;

        try {
            String name = new String(request.getParameter("name").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            String writer = new String(request.getParameter("writer").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            String classify = new String(request.getParameter("classify").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            float price = Float.parseFloat(request.getParameter("price"));

            Book book = new Book(name, price, writer, classify, "未借");
            boolean success = dao.addBook(book);
            if (success) {
                message = "成功添加一本图书";
            } else {
                message = "添加图书失败!";
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "添加图书失败!";
        }
        request.setAttribute("result", message);
        request.getRequestDispatcher("/manageBooks.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
